package com.atguigu.lease.web.admin.config;

import com.atguigu.lease.model.enums.BaseEnum;
import com.atguigu.lease.model.enums.ReleaseStatus;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author 86188
 * @version v1.0
 * @project ShangTingApartment
 * @Date 2025/7/8 23:35
 * @company []
 * @description
 */

@Configuration
public class MyWebConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory((new StringToBaseEnumStatusConverterFactory()));
    }
    static class StringToBaseEnumStatusConverterFactory implements ConverterFactory<String, BaseEnum> {
        @Override
        public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
            return new Converter<String, T>() {
                @Override
                public T convert(String source) {
                    //Class.getEnumConstants()方法四java反射API中的一个方法，用于获取表示枚举类型的Class对象中所有枚举常量的数组
                    for (T enumConstant : targetType.getEnumConstants()) {
                        if (enumConstant.getCode().equals(Integer.valueOf(source))){
                            return enumConstant;
                        }
                    }
                    throw new IllegalArgumentException("非法的枚举值："+source);
                }
            };
        }
    }
}